import React, { Component, useState, useEffect } from 'react'
import { Text, View, StyleSheet, Modal, Image, Dimensions, TextInput, TouchableWithoutFeedback, PermissionsAndroid, Clipboard, TouchableOpacity, ActivityIndicator } from 'react-native'
import { connect } from 'react-redux'
import { Cell, Popup } from '@pingtou/rn-vant'
import { asyncGetUserInfo } from "../../redux/features/appSlice"
import { grade } from "../../utils/grade"
import { pTx } from "../../utils/dimensions"
import { launchImageLibrary } from 'react-native-image-picker';
import { Provider, Button, InputItem, Toast } from '@ant-design/react-native'
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import Realm from "realm"
import httpApi from "../../api"
import Avatar from "../../components/avatar"

const MineDetailsList = (props) => {
    const [loading, setLoading] = useState(false)
    const [visible, setVisible] = useState(false)
    const [visible2, setVisible2] = useState(false)
    const [curFiles, setCurFiles] = useState([])
    const realm = useRealm();
    const userInfo = useQuery(schemaName.UserInfo, user => {
        return user.filtered('Current = true');
    })[0];
    const [nickname, setNickname] = useState(userInfo.NickName)

    const setUserInfoName = async () => {
        try {
            if (!nickname) return
            setLoading(true)
            const res = await httpApi.setUserNickName({ nickname })
            if (res.code == 20) {
                realm.write(() => {
                    userInfo.NickName = nickname
                })
            }
        } catch (error) {
        }
        setLoading(false)
        setVisible(false)
    }
    const setUserInfoImage = async () => {
        try {
            setLoading(true)
            const image = await httpApi.uploadMinio(curFiles)
            if (!image.data.FileNames[0]) return
            const res = await httpApi.setUserProfilePhoto({ profilePhoto: image.data.FileNames[0] })
            if (res.code == 20) {
                realm.write(() => {
                    userInfo.ProfilePhoto = image.data.FileNames[0]
                })
            }
        } catch (error) {
            console.log(error)
        }
        setLoading(false)
        setVisible2(false)
    }
    const cameraPermission = async () => {
        launchImageLibrary({
            mediaType: 'photo',
            maxWidth: 500,
            maxHeight: 500,
            quality: 0.5,
            videoQuality: 'low',
            includeBase64: true
        }, res => {
            if (res.didCancel) {
                return false;
            } else {
                const curFiles = res.assets
                setCurFiles(curFiles)
            }
        })
    }
    useEffect(() => {
        if (Platform.OS === 'android') {
            try {
                PermissionsAndroid.request(
                    PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                    {
                        title: '需要访问相册',
                        message: '需要访问相册',
                        buttonPositive: '',
                    },
                ).then(granted => {
                    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                        // this.setState({
                        //     granted: true,
                        // })
                    } else {
                        // this.setState({
                        //     granted: false,
                        // })
                    }
                })

            } catch (err) {
                console.warn(err)
            }
        }
    }, [])
    const copyToClipboard = () => {
        Clipboard.setString(userInfo.Address)
        Toast.info('复制成功')
    }

    return (
        <View>
            <Cell.Group>
                <Cell title="头像" center onPress={() => setVisible2(true)} value={<Avatar style={styles.Image} source={{ uri: userInfo.ProfilePhoto }}></Avatar>} />
                <Cell title="昵称" center isLink onPress={() => setVisible(true)} value={userInfo.NickName} />
                <Cell title="等级" center style={styles.row} value={<Image style={styles.infoCotentImage} source={grade[userInfo.UserLevel]}></Image>} />
            </Cell.Group>

            <Cell.Group style={styles.Group} >
                <Cell title="ID" center onPress={() => copyToClipboard()} value={<Text style={styles.address}>0x{userInfo.Address}</Text>} />
            </Cell.Group>
            <Modal
                animationType="fade"
                visible={visible}
                onRequestClose={() => setVisible(false)}
            >
                <View style={styles.Popup}>
                    <View style={styles.head}>
                        <Text style={styles.headText} onPress={() => setVisible(false)} >取消</Text>
                        <Text style={styles.headText}>设置名称</Text>
                        <TouchableOpacity disabled={loading} onPress={() => setUserInfoName()}>
                            <Text style={[styles.headText, styles.headbutton]}>
                                <>
                                    {loading ? <ActivityIndicator /> : "完成"}
                                </>
                            </Text>
                        </TouchableOpacity>
                    </View>
                    <TextInput
                        type={'text'}
                        maxLength={15}
                        style={styles.nickname}
                        value={nickname}
                        onChangeText={value => setNickname(value)}
                    >
                    </TextInput>
                </View>
            </Modal>

            <Modal
                animationType="fade"
                visible={visible2}
                onRequestClose={() => setVisible2(false)}
            >
                <View style={styles.ProfilePhotoPopup}>
                    <View style={styles.head}>
                        <Text style={styles.headText} onPress={() => setVisible2(false)} >取消</Text>
                        <Text style={styles.headText}>设置头像</Text>
                        <TouchableOpacity disabled={loading} onPress={() => setUserInfoImage()}>
                            <Text style={[styles.headText, styles.headbutton]}>
                                <>
                                    {loading ? <ActivityIndicator /> : "完成"}
                                </>
                            </Text>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.ProfilePhotoPopupBox}>
                        <TouchableOpacity onPress={() => cameraPermission()}>
                            {
                                curFiles[0]?.uri ? <Image
                                    style={styles.ProfilePhotoPopupImage}
                                    source={{ uri: curFiles[0]?.uri }} />
                                    : <Avatar style={styles.ProfilePhotoPopupImage} source={{ uri: userInfo.ProfilePhoto }}></Avatar>

                            }
                        </TouchableOpacity>
                    </View>
                </View>
            </Modal>
        </View>
    )
}

const mapStateToProps = (state) => {
    return {
    }
}

const mapDispatchToProps = {
    asyncGetUserInfo
}

export default connect(mapStateToProps, mapDispatchToProps)(MineDetailsList)

const styles = StyleSheet.create({
    Group: {
        marginTop: pTx(15),
    },
    Image: {
        width: pTx(40),
        height: pTx(40),
        borderRadius: pTx(6),
        backgroundColor: "#AFB5BD"
    },
    infoCotentImage: {
        marginLeft: pTx(8),
        width: pTx(34),
        height: pTx(16),
    },
    address: {
        fontSize: pTx(12),
        color: "#AFB5BD",
        maxWidth: Dimensions.get('screen').width - pTx(150),
    },
    Popup: {
        flex: 1,
        backgroundColor: "#EDEDED"
    },
    nickname: {
        backgroundColor: "#fff"
    },
    ProfilePhotoPopup: {
        flex: 1,
    },
    ProfilePhotoPopupBox: {
        flex: 1,
        marginTop: pTx(50),
        flexDirection: 'row',
        justifyContent: "center",
    },
    ProfilePhotoPopupImage: {
        width: pTx(200),
        height: pTx(200),
        backgroundColor: "#fff"
    },
    head: {
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
        paddingHorizontal: pTx(15),
        backgroundColor: "#f3f4f5",
        paddingVertical: pTx(10),
    },
    headText: {
        flex: 1,
        paddingVertical: pTx(5),
        fontSize: pTx(14),
        color: "#0A0C14",
    },
    headbutton: {
        backgroundColor: "#06C161",
        paddingHorizontal: pTx(12),
        borderRadius: pTx(6),
        color: "#fff"
    }
})